from typing import List
from fastapi import APIRouter, HTTPException, Security, Query
from pydantic import BaseModel
from core.Auth import check_permissions
from core.Response import Status, fail, res_antd, success
from models.base import Config, ConfigGroup
from tortoise.queryset import F

from schemas.backend.config import ConfigGroupList, UpdateConfigValueItem, UpdateConfigValueListReq

router = APIRouter()

@router.get("/group/{group_id}", summary="获取某组的配置项", dependencies=[Security(check_permissions, scopes=["config_query"])])
async def get_config(group_id: int):
    """
    获取某组的配置项
    :param group_id: 组ID
    :return:
    """
    try:
        config_group = await ConfigGroup.get_or_none(id=group_id)
        if not config_group:
             return fail(msg='组不存在')
        configs = await Config.filter(group=group_id).all()
        return success(data=configs)
    except Exception as e:
        return fail(msg=str(e))

@router.get("/group_list", response_model=ConfigGroupList, summary="获取所有组列表", dependencies=[Security(check_permissions, scopes=["config_query"])])
async def get_group_list():
    """
    获取所有组列表
    :return:
    """
    try:
        groups = await ConfigGroup.annotate(title=F('group_title')).filter(status=1).filter(types=1).values('id','title')
        return success(data=groups)
    except Exception as e:
        return fail(msg=str(e))

# 编辑配置项
@router.put("/batch", summary="批量更新配置项", dependencies=[Security(check_permissions, scopes=["config_update"])])
async def batch_update_config(configs: List[UpdateConfigValueItem]):
    """
    批量更新配置项
    :param configs:
    :return:
    """
    # 验证数据
    if not configs or not all(hasattr(c, 'id') and hasattr(c, 'config_value') for c in configs):
        return fail(msg='参数不正确')
    try:
        config_instances = []
        for config_data in configs:
            config = await Config.get_or_none(id=config_data.id)
            if not config:
                raise HTTPException(status_code=404, detail=f"Config with id {config_data.id} not found")
            config.config_value = config_data.config_value
            config_instances.append(config)

        # 执行批量更新
        await Config.bulk_update(config_instances, fields=["config_value"])
        return success(msg='更新成功')
    except Exception as e:
        return fail(msg=str(e))

